package com.xinzhitong.www.utils;

import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;

/**
 * 驼峰工具
 *
 * @author 徐鑫
 */
public class CamelCase {
    /**
     * 驼峰命名法
     *
     * @param str 原下划线字符串
     * @return 转化为驼峰字符串
     */
    public static String camelCase(String str) {
        StringBuilder builder = new StringBuilder();
        Arrays.asList(str.split("_")).forEach(temp -> builder.append(StringUtils.capitalize(temp)));
        return Character.toLowerCase(builder.charAt(0)) + builder.substring(1);
    }

    /**
     * 逆驼峰命名法
     *
     * @param str 原驼峰字符串
     * @return 下划线字符串
     */
    public static String reCamelCase(String str) {
        //开头小写
        StringBuilder res = new StringBuilder();
        res.append(Character.toLowerCase(str.charAt(0)));
        res.append(str.substring(1));
        str = res.toString();

        //转化为下划线字符串
        res = new StringBuilder();
        char[] chars = str.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] > 'Z' || chars[i] < 'A')
                res.append(chars[i]);
            if (chars[i] <= 'Z' && chars[i] >= 'A' && chars[i + 1] <= 'z' && chars[i + 1] >= 'a') {
                res.append('_');
                res.append(Character.toLowerCase(chars[i]));
            }
        }
        return res.toString();
    }
}
